<?php

class Quad_Spreadsheet {
	
	public $_rows = array();
	public $_headings = array();
	
	public function __construct($rs = null, $headings = null) {
		if (is_array($rs)) {
			$this->addRows($rs, $headings);
		}
	}
	
	public function addRows($rs, $headings = null) {
		$this->_rows = array_merge($this->_rows, $rs);
		if ($headings) {
			$this->setHeadings($headings);
		}
		return $this;
	}
	
	public function setRows($rs, $headings = null) {
		$this->clear();
		$this->addRows($rs, $headings);
		return $this;
	}
	
	public function getRows() {
		return $this->_rows;
	}
	
	public function clear() {
		$this->_rows = array();
		$this->_headings = array();
	}
	
	public function setHeadings($headings) {
		$this->_headings = $headings;
	}
	
	public function getHeadings() {
		return $this->_headings;
	}
	
	public function save($filename) {
		$fp = fopen($filename, 'w');
		$this->_write($fp);
		fclose($fp);
		// TODO: return success
	}
	
	public function sendAsAttachment($filename) {
//Quad_Debug::log('sendAsAttachment');		
		$fp = fopen('php://output', 'w');
		ob_end_clean();
		$this->_write($fp);
		header('Content-type: application/octet-stream');
		header("Content-Disposition: attachment; filename=\"$filename\"");
		fclose($fp);
	}	
	
	// To be implemented in child classes
	public function _write($fp) {}
	
}